#include "DoorAlertor.h"

#include "CommandParser.h"


DoorAlertor::DoorAlertor(DummyChannel& channel, const ExtendDeviceType& deviceType, const std::string& deviceActknowlege): ExtendDevice(channel, deviceType, deviceActknowlege)
    ,mpool(GuiContextSingleton::instance().getWorkPool()), mpcommandParser(&CommandParserSingleton::instance()) {

}



void DoorAlertor::commitToTaskPool(const DoorStatus doorStatus) {
    if (DoorStatus::OPENED == doorStatus) {
        BuzzerSingleton::instance().beep(BuzzerDataPtr(new BuzzerDataPtr::element_type{100000, 50000, 100000, 50000, 100000}));
    }
    Task* pTask = buildDynamicFunctor(&DoorAlertor::updateDoorStatus, this, doorStatus);
    mpool->pushPool(pTask);
}



bool DoorAlertor::recheck() noexcept {

    bool recheckResult = false;
    DoorStatus doorStatus = DoorStatus::ERROR;
    std::string result;
    try {
        mchannel.sendStringReturnString(std::string("<DOOR>"), result);
        if ("<DOOR_CLOSE>" == result) {
            doorStatus = DoorStatus::CLOSED;
            recheckResult = true;
        } else if ("<DOOR_ALARM>" == result) {
            doorStatus = DoorStatus::OPENED;
            recheckResult = true;
        }

        commitToTaskPool(doorStatus);
        mdeviceStatisticInfo.setCheckStatus(recheckResult);
    } catch (std::exception& ex) {
        LOG_ERROR(ex.what());
    }
    return recheckResult;
}

DoorStatus DoorAlertor::updateDoorStatus(const DoorStatus doorStatus, const Task* pTask) {
    if (doorStatus != mdoorStatus) {
        mdoorStatus = doorStatus;

        mpcommandParser->sendDoorStatus();
    }

    releaseDynamicFunctor(pTask);
    return mdoorStatus;
}









